import { onUnmounted, ref } from "vue";

export function useSetTimeoutTaskHook(f: Function, ms: number,autoStart?:boolean) {
  const taskId = ref<any>(null);
  if(autoStart){
    start()
  }
  /**
   * 页面卸载时自动清除定时器
   */
  // onUnmounted(() => {
  //   cancel();
  // });
  function start() {
    taskId.value = setTimeout(() => {
      f();
    }, ms);
  }
  function cancel() {
    if (taskId.value != null) {
      clearTimeout(taskId.value);
      taskId.value = null;
    }
  }
  return {
    taskId,
    start,
    cancel,
  };
}
